package com.tahoecn.compareFileList.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.tahoecn.compareFileList.service.FileService;
/**
 *  
 * @author 崔礼堂 cuilitang@126.com
 *页面后期再加
 */
@Controller
public class FileController {
	
	//定义一个全局的记录器，通过LoggerFactory获取
    private final static Logger logger = LoggerFactory.getLogger(FileController.class);
	
	//String absFilePath = "C:/landray/kmss/resource/";   
    @Value("${fileisexist.abspath}")
    String absFilePath;
    
    @Value("${fileisexist.exportpath}")
    String exportPath;
	
	@Autowired
	FileService fileService;
	
	
	 @ResponseBody
	@RequestMapping("/filecompare")
	public String findDBFilePathByDate(String dateStr,HttpServletResponse response) throws IOException {
		
		List<String> resultList = new ArrayList<String>();
		HashMap<String,Object> resultMap = new HashMap<String,Object>();
		
		if(dateStr ==null||dateStr.length()==0){
			resultMap.put("status", "dateStr为空");
			return resultMap.toString();
		}
		
		List<String> dbFilePathList = fileService.findFilePathByDate(dateStr);

		if(dbFilePathList ==null||dbFilePathList.size()==0){
			resultMap.put("status", "dbFilePathList为空");
			return resultMap.toString();
		}
		
		
		
		String[] yearMonth = dateStr.split("-");
		int month = Integer.parseInt(yearMonth[1]);
		String fullAbsFilePath = absFilePath+yearMonth[0]+"/"+month;
		
		
	 
		
		List<String> findOSFilePathByDateList = findOSFilePathByDate(fullAbsFilePath);
		
		if(findOSFilePathByDateList ==null){
			resultMap.put("status", "findOSFilePathByDateList为空");
			return resultMap.toString();
		}
    
		
		ArrayList<String> osNotExistFileNameList = new ArrayList<String>();
		
		for (String string : dbFilePathList) {
 			
			String dbFileName = string.substring(string.lastIndexOf("/")+1);
			/**
			 * 如果系统文件中没有数据库中的文件名，则存入数据库不存在osNotExistFileNameList
 			 */
		
			if(!findOSFilePathByDateList.contains(dbFileName)){
				osNotExistFileNameList.add(dbFileName);
 			}
	 
		}
		
		/**
		 * 迭代系统不存在文件名，过滤扩展名问题
 		 * 		
		 */
		for (String dbName : osNotExistFileNameList) {
			int flag = 0;
			for (String osName : findOSFilePathByDateList) {
				
				boolean osNameConatinsDbName = osName.contains(dbName);
				boolean dbNameConatinsOsName = dbName.contains(osName);
				if(osNameConatinsDbName||dbNameConatinsOsName){
					//两者有包含关系，则使用  ==》连接起来，跳出内层循环
					resultList.add(dbName+"==》"+osName);
					flag = 1;
					break;
				}
				//没有包含关系，只存dbName
			}
			if(flag == 0){
				resultList.add(dbName);
			}
		}
		
		File writeFile = writeFile(resultList);
		//sendFileToResponse(writeFile,writeFile.getName(),response);
		resultMap.put("status","OK");
		resultMap.put("fileName",writeFile.getAbsolutePath());
		
	
		return resultMap.toString();
		
	} 
	
	private void sendFileToResponse(File file,String fileName,HttpServletResponse response) throws IOException{
	 	// 以流的形式下载文件。
	 			InputStream fis = new BufferedInputStream(new FileInputStream(file));
	 			byte[] buffer = new byte[fis.available()];
	 			fis.read(buffer);
	 			fis.close();
	 			
	 			response.reset();
	 			// 设置response的Header
	 			response.addHeader("Content-Disposition", "attachment;filename="
	 					+ URLEncoder.encode(fileName,"utf-8")); 
	 	 		response.addHeader("Content-Length", "" + file.length());
	 			OutputStream toClient = new BufferedOutputStream(
	 					response.getOutputStream());
	 	 		toClient.write(buffer);
	 			toClient.flush();
	 			toClient.close();
	 	}	
	private File writeFile(List<String> resultList) throws FileNotFoundException {
		File file = new File(exportPath+"/resultList"+new Date().toLocaleString().replace(":", "_")+".txt");
        FileOutputStream fos1 = new FileOutputStream(file, true);
        // 创建FileOutputStream对应的PrintStream，方便操作。PrintStream的写入接口更便利
        PrintStream out1 = new PrintStream(fos1);
        out1.print("不存在的文件个数："+resultList.size()+"\r\n");
        for (String string : resultList) {
             out1.print(string+"\r\n");
 		}
        out1.close();
		return file;
 
	}
	
	private List<String> findOSFilePathByDate(String absFilePath) {
		
 		
		 // 获得指定文件对象  
        File file = new File(absFilePath);   
        // 获得该文件夹内的所有文件   
        String[] array = file.list();   
        if(array == null){return null;}  //TODO
         
        
        return Arrays.asList(array);
		
	} 
	
	
	public static void main(String[] args) {
		
		String string = "C:/landray/kmss/resource/666.ttt";
		String fileName = string.substring(string.lastIndexOf("/")+1);
		System.out.println(fileName);
		System.out.println(string.contains("."));
		
	}
		
	 
	
	

}
